<template>
  <div class="avatar-wrap" :style="{ width: `${(radius * 2) / 16}rem`, height: `${(radius * 2) / 16}rem` }">
    <EncryptImage
      class="avatar"
      :class="{ 'white-border': hasBorder }"
      v-bind="$props"
      :full-src="fullSrc"
      fail-src="/images/avatar.png"
      object-fit="cover"
      rounded
      @load-fail="loadFail = true"
      :click-to-full="clickToFull"
    ></EncryptImage>
    <img
      v-if="vip && vipTier <= 1"
      class="frame"
      src="/images/premium/avatar-frame.png"
      :style="{ width: avatarBorderWidth, height: avatarBorderHeight, transform: avatarBorderTransform }"
    />
    <img
      v-if="vipTier > 1"
      :src="`/images/avatar-bg${vipTier}.png`"
      class="frame"
      alt=""
      :style="{ width: avatarBorderWidth, height: avatarBorderHeight, transform: avatarBorderTransform }"
    />
    <slot name="decorator"></slot>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import EncryptImage from '@/components/multimedia/EncryptImage.vue'

const props = defineProps({
  src: { type: String },
  fullSrc: { type: String },
  radius: { type: Number },
  border: { type: Boolean, default: false },
  clickToFull: { type: Boolean, default: false },
  vip: { type: Boolean, default: false },
  vipTier: { type: Number, default: 0 },
})

const loadFail = ref(false)
const hasBorder = computed(() => props.border || loadFail.value)

const avatarBorderWidth = computed(() => `${(props.radius * 2) / 16 / (80 / 102)}rem`)
const avatarBorderHeight = computed(() => `${(props.radius * 2) / 16 / (80 / 91)}rem`)
const avatarBorderTransform = computed(
  () => `translate(-${(props.radius * 2) / 16 / (80 / 12)}rem, -${(props.radius * 2) / 16 / (80 / 86)}rem)`,
)

watch(
  () => props.src,
  () => (loadFail.value = false),
)
</script>

<style lang="scss" scoped>
.avatar-wrap {
  position: relative;

  .avatar.white-border {
    border: 0.0625rem solid #fff;
  }

  .frame {
    position: absolute;
    pointer-events: none;
  }
}
</style>
